package com.server.llh.llhserverwork.activity.server;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.BaseFragment;
import com.server.llh.llhserverwork.adapter.ServerOrderInfosAdapter;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.OldManInfo;
import com.server.llh.llhserverwork.bean.StockDetailPage;
import com.server.llh.llhserverwork.port.QuitCloseIntetface;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by ZTF on 2017-03-28.
 */

public class LlhServerSubscribeFragment extends BaseFragment   {
    Unbinder unbinder;
    @BindView(R.id.query_subscribe)
    ListView querySubscribe;
    SwipeRefreshLayout refrashData;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;
    final static String TAG = "LlhServer";
    private List<StockDetailPage> stockDetailPageList = new ArrayList<>();
    View rootView;
    private String userIdStr, userNameStr, userPhoneStr, token;
    OldManInfo oldManInfo = null;
    public static LlhServerSubscribeFragment newInstance(String userId) {
        Bundle bundle = new Bundle();
        bundle.putString("userId", userId);
        LlhServerSubscribeFragment fragment = new LlhServerSubscribeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        userIdStr = SharedPreferenceUtil.getUserInfo("customerId", getActivity().getApplicationContext());
        token = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getActivity().getApplicationContext());
            oldManInfo = new OldManInfo();
            oldManInfo.setUserId(userIdStr);
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            isPrepared = true;
//            lazyLoad();
        }
        refrashData = (SwipeRefreshLayout) rootView.findViewById(R.id.refrash_data);
        refrashData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onRefreshReq();
            }
        });
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void onRefreshReq() {
        if (mHasLoadedOnce == false || isPrepared == false || mHasLoadedOnce) {
            mHasLoadedOnce = true;
            isPrepared = true;
            mHasLoadedOnce = false;
        }
        lazyLoad();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume==");
        onRefreshReq();
     }

    //请求数据
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
       /* stockDetailPageList.clear();
        if (serverOrderInfosAdapter!=null){
            serverOrderInfosAdapter.notifyDataSetChanged();
        }*/
        reqServerKucun(userIdStr);
    }

    ServerOrderInfosAdapter serverOrderInfosAdapter;

    private void reqServerKucun(String customerId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("userId", customerId);
        lRequest.addParam("token", token);
        lRequest.addParam("orgId", SharedPreferenceUtil.getUserInfo(Constants.UserInfo.CHAIN_ID,getActivity().getApplicationContext()));
        lRequest.addParam("supplierId", SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,getActivity().getApplicationContext()));
        lRequest.setUri(ServerPort.GET_STOCK_ON_TYPE);
        lRequest.setUriType(UrlsTools.SERVER_KUC_INFO);
        lRequest.setType(String.class);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                try {
                    if (refrashData!=null){
                        refrashData.setRefreshing(false);
                    }
                    closeProgress();
                    T.showAnimErrorToast(getActivity().getApplicationContext(), "请求超时！");
                } catch (Exception E) {

                }
            }

            @Override
            public void onNext(String responseBean, String code) {
                try {
                    if (refrashData!=null){
                        refrashData.setRefreshing(false);
                    }
                    closeProgress();
                    Log.d(TAG, "responseBean==" + responseBean.toString());
                    stockDetailPageList.clear();
                    if (responseBean != null && "200".equals(code)) {
                        stockDetailPageList = new Gson().fromJson(responseBean, new TypeToken<List<StockDetailPage>>() {
                        }.getType());
                        if (stockDetailPageList != null && stockDetailPageList.size() > 0) {
                            serverOrderInfosAdapter = new ServerOrderInfosAdapter(getActivity(), stockDetailPageList, oldManInfo);
                            querySubscribe.setAdapter(serverOrderInfosAdapter);
                            serverOrderInfosAdapter.notifyDataSetChanged();
                        }
                        mHasLoadedOnce = true;
                    } else {
                        T.showAnimToast(getActivity().getApplicationContext(), "抱歉暂时没有可预约的服务！");
                        mHasLoadedOnce = true;
                        stockDetailPageList.clear();
                        serverOrderInfosAdapter.notifyDataSetChanged();
                     }
                } catch (Exception E) {
                }
            }
        });
    }

    @Override
    public void showProgress() {
        try {
            if (refrashData!=null){
                refrashData.setRefreshing(false);
            }
            showProgress(LlhServerSubscribeFragment.this.getActivity());
        } catch (Exception e) {
        }

    }

    @Override
    public void hideProgress() {
        try {
            if (refrashData!=null){
                refrashData.setRefreshing(false);
            }
            closeProgress();
        } catch (Exception e) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public int getLayoutView() {
        return R.layout.llh_server_subscribe;
    }

    @Override
    public void initView(View view) {
    }

    @Override
    public void doBases() {

    }


}
